<template>
  <div style="width:100%;height: 100%;background-color: rgb(41, 42, 45);">
    <div style="display: flex;flex-direction: column;padding: 3vh 3vh;justify-content: space-between;height: 100%;width: 100%;">
      <div class="messageContent">
        <div style="width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;max-height: 100%;">
          <ConfigProvider
              v-for="({ algorithm, background }, index) in items"
              :key="index"
              :theme="{ algorithm }"
          >
            <Welcome
                v-if="chatList.length == 0"
                class="welcome"
                :style="{ backgroundImage: background, borderStartStartRadius: 4,width: '50%' }"
                icon="https://document-yd.oss-cn-beijing.aliyuncs.com/icon/logo.png"
                title="Hello , I'm Koala , Nice to meet you!"
                description="Koala致力于实现全任务场景下自编程、自发布、自部署，加速AGI普惠人类"
            />

            <t-chat
                animation="skeleton"
                v-else
                :reverse="true"
                style="width: 80%;"
                :data="chatList"
                :text-loading="loading"
                :isStreamLoad="isStreamLoad"
            >

              <template #actions="{ item, index }">
                <t-chat-action
                    :content="item.content"
                    :operation-btn="['good', 'bad', 'replay', 'copy']"
                    @operation="handleOperation"
                />
              </template>
            </t-chat>
          </ConfigProvider>
        </div>
      </div>
      <div class="input" style="padding: 0 10%;">
        <t-chat-sender
            ref="chatSenderRef"
            class="chat-sender"
            :stop-disabled="loading"
            :textarea-props="{
      placeholder: '请输入消息...',
    }"
            @send="inputEnter"
        >
          <template #prefix>
            <div class="model-select">
              <t-tooltip v-model:visible="allowToolTip" content="切换模型" trigger="hover">
                <t-select
                    v-model="selectValue"
                    :options="selectOptions"
                    value-type="object"
                    @focus="allowToolTip = false"
                ></t-select>
              </t-tooltip>
              <t-button class="check-box" :class="{ 'is-active': isChecked }" variant="text" @click="checkClick">
                <SystemSumIcon />
                <span>深度思考</span>
              </t-button>
            </div>
          </template>
        </t-chat-sender>

        <p style="font-weight: bolder;margin-top: 20px;display: flex;flex-direction: column;align-items: center">
          <span>© 2025 Byte. 本产品开源协议遵守
            <a href="https://opensource.org/licenses/MIT">MIT License</a>. 本产品包含第三方贡献者开发的软件
          </span>
        </p>

      </div>
    </div>


  </div>
</template>
<script setup lang="ts">
import {
  ConfigProvider,
  theme,
} from 'ant-design-vue';
import {Welcome} from 'ant-design-x-vue';
import {h, ref} from "vue";
import { SystemSumIcon } from 'tdesign-icons-vue-next';
import {sendMessage} from "@/chat/spark/index";
defineOptions({ name: 'AXSenderSendStyle' })

const isStreamLoad = ref(false);
const loading = ref(false);
const allowToolTip = ref(false);
const chatSenderRef = ref(null);
const selectOptions = [
  {
    label: '默认模型',
    value: 'default',
  },
  {
    label: 'Deepseek',
    value: 'deepseek-r1',
  },
  {
    label: '混元',
    value: 'hunyuan',
  },
];
const selectValue = ref({
  label: '默认模型',
  value: 'default',
});
const isChecked = ref(false);
const checkClick = () => {
  isChecked.value = !isChecked.value;
};
// 消息发送
const inputEnter = async function (inputValue: string) {
  if (loading.value) {
    return;
  }
  if (!inputValue) return;
  loading.value = true;
  isStreamLoad.value = true;
  const userMessage = {
        avatar: 'https://tdesign.gtimg.com/site/avatar.jpg',
        content: inputValue,
        role: 'user',
    name: '你',
    datetime: formatTime(new Date()),
  }
  const botMessage = {
    avatar: '/src/assets/logo/logo.png',
    content: '',
    role: 'assistant',
    name: 'Koala',
    datetime: formatTime(new Date()),
  }
  chatList.value.unshift(userMessage)
  // 空消息站位
  chatList.value.unshift(botMessage)

  await handleData(inputValue)
  isStreamLoad.value = false;
};

// 发送问题
const handleData = async (inputValue) => {
  const lastItem = chatList.value[0]

  const response =  await sendMessage(inputValue)
  loading.value = false;
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split('\n');
    // 保留未处理完的部分（最后一个可能是不完整的行）
    buffer = lines.pop() || '';
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const dataStr = line.replace('data: ', '').trim();
        if (dataStr === '[DONE]') {
          console.log('Stream finished');
          return;
        }
        try {
          const data = JSON.parse(dataStr);
          const content = data.choices[0]?.delta?.content || '';
          if (content) {
            lastItem.content += content;
          }
        } catch (e) {
          console.error('Failed to parse SSE data:', e);
        }
      }
    }
  }
}

// 点击操作按钮
const handleOperation = function (type, options) {
  console.log('handleOperation', type, options);
};

// 消息
const chatList = ref([])

const items: {
  algorithm: typeof theme.defaultAlgorithm;
  background: string;
}[] = [
  {
    algorithm: theme.darkAlgorithm,
    background:
        'linear-gradient(97deg, rgba(90,196,255,0.12) 0%, rgba(174,136,255,0.12) 100%)',
  },
];


function formatTime(timestamp) {
  const date = new Date(timestamp);
  const now = new Date();
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);

  // 格式化时间为 HH:mm
  const timeStr = date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  }).replace(/^24/, '00'); // 处理24点的情况

  if (date >= today) {
    return `今天 ${timeStr}`;
  } else if (date >= yesterday) {
    return `昨天 ${timeStr}`;
  } else {
    // 更早的日期显示 yyyy-MM-dd HH:mm
    const dateStr = date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).replace(/\//g, '-');
    return `${dateStr} ${timeStr}`;
  }
}

</script>


<style lang="less">

.welcome *{
  color: white !important;
}

.messageContent {
  flex: 11;
  overflow-y: scroll;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
}
.input {
  flex:2;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.input * {
  color: white !important;
}



/* 应用滚动条样式 */
::-webkit-scrollbar-thumb {
  background-color: var(--td-scrollbar-color);
}
::-webkit-scrollbar-thumb:horizontal:hover {
  background-color: var(--td-scrollbar-hover-color);
}
::-webkit-scrollbar-track {
  background-color: var(--td-scroll-track-color);
}
/**发送框 **/

.chat-sender {
  .btn {
    color: var(--td-text-color-disabled);
    border: none;
    &:hover {
      color: var(--td-brand-color-hover);
      border: none;
      background: none;
    }
  }
  .btn.t-button {
    height: var(--td-comp-size-m);
    padding: 0;
  }
  .model-select {
    display: flex;
    align-items: center;
    .t-select {
      width: 112px;
      height: var(--td-comp-size-m);
      margin-right: var(--td-comp-margin-s);
      .t-input {
        border-radius: 32px;
        padding: 0 15px;
      }
      .t-input.t-is-focused {
        box-shadow: none;
      }
    }
    .check-box {
      width: 112px;
      height: var(--td-comp-size-m);
      border-radius: 32px;
      border: 0;
      background: var(--td-bg-color-component);
      color: var(--td-text-color-primary);
      box-sizing: border-box;
      flex: 0 0 auto;
      .t-button__text {
        display: flex;
        align-items: center;
        justify-content: center;
        span {
          margin-left: var(--td-comp-margin-xs);
        }
      }
    }
    .check-box.is-active {
      border: 1px solid var(--td-brand-color-focus);
      background: var(--td-brand-color-light);
      color: var(--td-text-color-brand);
    }
  }
}
</style>
